<?php

namespace app\common\logic;
use think\Db;
use think\exception\ValidateException;


/**
 * 单位逻辑曾
 */
class OrgLogic
{
   //获取当前单位所属的顶级单位方法
    protected $orgCate = null;
    public function __construct()
    {
        $this->orgCate = Db::name('org_cate');
    }

    /**
     * @$org_cate_id 单位id 最顶级
     */
    public function getOneLevel($org_cate_id) {
        $cur = $this->orgCate->find($org_cate_id);
        if (!$cur) {
            throw new ValidateException('获取单位信息错误');
        }

        if ($cur['parent_id'] == 0) {
            //顶级
            return $cur;
        } else {
            //查找上级的id
            $this->getOneLevel($cur['parent_id']);
        }
    }

    public function getCateChild($org_cate_id){
        $ids = $this->orgCate->where('parent_id',$org_cate_id)->column('id');
        if($ids){
            $ids = array_merge($ids,[$org_cate_id]);
            $ids = $this->orgCate->where('parent_id','in',$ids)->column('id');
        }
        $ids = array_merge([$org_cate_id], $ids);
        return $ids;
    }

    /**
     * @$org_cate_id 验证单位是否最顶级
     * 选择单位必须是最顶级
     */
    public function check($org_cate_id) {
        $cur = $this->orgCate->find($org_cate_id);
        if ($cur['parent_id'] != 0) {
            throw new ValidateException('单位选择不正确');
        }

        return true;
    }
        
    /**
     * 单位搜索
     */
    public function search($search) {
        $where['level'] = 1;
        $where['status'] = 0;
        $where['name'] = $search;
        $list = $this->orgCate->where($where)->order('createtime desc')->limit(1)->field('id, name,type')->select();

        return $list;
    }

    public function checkMobile($mobile)
    {
        $total = $this->orgCate->where('mobile', $mobile)->where('parent_id', 0)->count();
        if($total > 0){
            return false;
        }
        $total = Db::name('admin')->where('mobile', $mobile)->where('org_cate_id', '>', 0)->count();
        if($total > 0){
            return false;
        }
        $total = Db::name('org_reply')->where('mobile', $mobile)->count();
        if($total > 0){
            return false;
        }
        return true;
    }

    public function checkName($name)
    {
        $total = $this->orgCate->where('name', $name)->where('parent_id', 0)->count();
        if($total > 0){
            return false;
        }
        $total = Db::name('org_reply')->where('name', $name)->count();
        if($total > 0){
            return false;
        }
        return true;
    }
}
